package com.pingzi.code.controller;

import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test1")
    public String test1(){
        // 获取锁 默认 非公平锁
        RLock lock = redissonClient.getLock("staff_10_key");
        // RLock fairLock = redissonClient.getFairLock("staff_1_key");

        try {
            // 加锁 有效期默认30秒
            lock.lock();

            // 指定锁的有效时间
            // lock.lock(10, TimeUnit.SECONDS);

            // 指定超时时间 100 秒;锁的有效时间 10 秒
            // lock.tryLock(100, 10, TimeUnit.SECONDS);

            // 执行具体逻辑...
            // 执行过程中，不能修改锁
            RBucket<String> bucket = redissonClient.getBucket("name");
            bucket.set("zhaoyun");
            System.out.println(bucket.get());
            Thread.sleep(50000);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (lock != null) {
                // 释放锁
                lock.unlock();
            }
        }
        return "hello : ";
    }

    @GetMapping("/test2")
    public String test2(){
        // 获取锁 默认 非公平锁
        RLock lock = redissonClient.getLock("staff_10_key");

        try {
            // 加锁
            lock.tryLock(20, 10, TimeUnit.SECONDS);
            System.out.println("超时");
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (lock != null) {
                // 释放锁
                lock.unlock();
            }
        }
        return "hello : ";
    }
}
